package com.shuai.AI.demo.invoke;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.shuai.AI.demo.constants.CommonsUtil;
import java.util.HashMap;
import java.util.Map;

public class HttpAiInvoke {
  public static void main(String[] args) {
    /** 从环境变量里获取API密钥 */
    //    // 替换为你的API密钥
    //    String apiKey = System.getenv("DASHSCOPE_API_KEY");
    //    if (apiKey == null || apiKey.isEmpty()) {
    //      System.err.println("请设置环境变量 DASHSCOPE_API_KEY");
    //      return;
    //    }

    String apiKey = CommonsUtil.API_KEY;

    // 构建请求URL
    String url = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions";

    // 构建请求体
    Map<String, Object> requestBody = new HashMap<>();
    requestBody.put("model", "qwen-plus");

    // 构建messages数组
    JSONArray messages = new JSONArray();

    // 添加system消息
    JSONObject systemMessage = new JSONObject();
    systemMessage.put("role", "system");
    systemMessage.put("content", "You are a helpful assistant.");
    messages.add(systemMessage);

    // 添加user消息
    JSONObject userMessage = new JSONObject();
    userMessage.put("role", "user");
    userMessage.put("content", "你是谁？");
    messages.add(userMessage);

    requestBody.put("messages", messages);

    // 转换为JSON字符串
    String jsonBody = JSON.toJSONString(requestBody);

    // 发送POST请求
    try (HttpResponse response =
        HttpRequest.post(url)
            .header("Authorization", "Bearer " + apiKey)
            .header("Content-Type", "application/json")
            .body(jsonBody)
            .execute()) {

      // 处理响应
      System.out.println("响应状态码: " + response.getStatus());
      System.out.println("响应内容: " + response.body());

      // 如果需要解析响应JSON，可以使用FastJSON2
      if (response.isOk()) {
        JSONObject responseJson = JSON.parseObject(response.body());
        // 可以根据需要提取响应中的数据
        // 例如：String answer = responseJson.getJSONArray("choices")
        //     .getJSONObject(0).getJSONObject("message").getString("content");
      }
    } catch (Exception e) {
      System.err.println("请求发生错误: " + e.getMessage());
      e.printStackTrace();
    }
  }
}
